<?php
/**
 * @category Grids: The Powerful Grid
 * @tutorial Learn most of the features of the Grid model.
 * @author Mario Di Vece <mario@unosquare.com>
 */
class GridSampleWidget extends WidgetBase
{
    public function __construct()
    {
        parent::__construct(__CLASS__);
        Resources::setUserCulture(CultureInfo::CULTURE_ESMX);
        // 4. Create the grid and add some column mappings to the data source
        $grid = new Grid('gridStock', 'Product Stock Tracking');
        
        $grid->addColumn(new GroupingColumn('product', ''));
        $grid->addColumn(new DateTimeBoundGridColumn('change_date', 'Date'));
        $grid->addColumn(new NumberBoundGridColumn('change_stock', 'Change'));
        $grid->addColumn(new NumberBoundGridColumn('new_stock', 'New Stock'));
        $grid->addColumn(new TextBoundGridColumn('user_comment', 'Comment', 200, 'products_stock_tracking.user_comment'));
        $grid->addColumn(new NumberBoundGridColumn('order_id', 'Order ID', 'order_id'));
        
        // 5. Add some actions to the rows of the grid
        //$grid->addColumn(new RowCommandGridColumn('select', 'Detalles', 'DetailsSelected', 'order_id')); // A grid column with predefined command captions
        //$grid->addColumn(new RowCommandGridColumn('toggle', '', 'DetailsSelected', 'order_id', 'habilitado')); // A grid column with databound command captions
        $grid->addColumn(new DetailsCommandGridColumn('details', 'DetailsSelected', 'change_date'));
        $grid->addColumn(new EditCommandGridColumn('edit', 'DetailsSelected', 'change_date'));
        $grid->addColumn(new DeleteCommandGridColumn('delete', 'DetailsSelected', 'change_date'));
        $grid->addColumn(new SelectCommandGridColumn('select', 'DetailsSelected', 'change_date'));
        
        // 6. Setup some quick filters
        $grid->getFilteringManager()->addFilter('Good Stock (Above 90)', 'products.stock >= 90');
        $grid->getFilteringManager()->addFilter('Low Stock (Below 90)', 'products.stock < 90');
        
        // 7. Let's add some printing and exporting capabilities with a custom action
        $gridPrinter = new GridPrintEventManager('gridPrinter');
        $grid->getChildren()->addControl($gridPrinter);
        $gridBiffExporter = new GridBiffExporterEventManager('gridBiffExporter');
        $grid->getChildren()->addControl($gridBiffExporter);
        $gridOxmlExporter = new GridOxmlExporterEventManager('gridOxmlExporter');
        $grid->getChildren()->addControl($gridOxmlExporter);
        $gridCsvExporter = new GridCsvExporterEventManager('gridCsvExporter');
        $grid->getChildren()->addControl($gridCsvExporter);
        
        // 8. Setup the page size, default sort order, and register event handlers for action columns
        $grid->setPageSize(10);
        $grid->setDefaultSort('change_date', GridState::GRID_SORT_DESCENDING);
        
        $this->model = $grid;
        
        Controller::registerEventHandler('DetailsSelected', array(
            __CLASS__,
            'onGrid_DetailsSelected'
        ));
        
        // 12. Create the view (the HTML version of it)
        $gridView   = new HtmlGridView($grid);
        $this->view = $gridView;
    }
    
    /**
     * 11. Implement a handler: Handles the Grid_DetailsSelected event
     * 
     * @param Grid $model
     * @param ControllerEvent $event
     */
    public static function onGrid_DetailsSelected(&$model, &$event)
    {
        //Controller::transfer('testbed.php');
        $message = 'Server event raised: ' . $event->getName() . ' = ' . $event->getValue();
        $model->setMessage($message);
    }
    
    public function handleRequest()
    {
        // 3. Setup a datasource using an autogenerated DataContext (app.settings dependent)
        $dataContext = DataContext::getInstance();
        $dataSource  = $dataContext->getAdapter('products_stock_tracking'); // get the main table
        $dataSource
            ->joinRelated('products') // Automatically apply joins from metadata for main table
            ->innerJoin('categories', 'products.category_id = categories.id') // Establish a manual join for indirect relations
            ->addField('products_stock_tracking', 'change_date') // add some fields
            ->addField('products_stock_tracking', 'change_stock')
            ->addField('products_stock_tracking', 'new_stock')
            ->addField('products_stock_tracking', 'user_comment')
            ->addField('products_stock_tracking', 'order_id', 'order_id');
        
        if (ObjectIntrospector::isClass($dataSource->getConnection(), 'MsSqlConnection'))
            $dataSource->addFunctionField("categories.name + ': ' + products.name + ' ' + products.title + ': ' + CAST(products.stock AS varchar) + ' in stock'", 'product');
        else
            $dataSource->addFunctionField("CONCAT(categories.name, ': ', products.name, ' ', products.title, ': ', products.stock, ' in stock')", 'product');
        
        // 9. Handle the events
        if (Controller::isPostBack($this->model))
            Controller::handleEvents($this->model);
        
        // 10. After all the events are done, bind to the datasource
        $this->model->dataBind($dataSource);
        
        // 13. AJAX support: Only send out the updated markup if the view is asynchronous. Otherwise, let the page run normally
        if (Controller::isPostBack($this->model) && $this->view->getIsAsynchronous())
        {
            $this->view->render();
            exit();
        }
    }
    
    public static function createInstance()
    {
        return new GridSampleWidget();
    }
}
$sample = new GridSampleWidget();
$sample->handleRequest();